<template>
  <a-modal
    v-model:open="visible"
    title="本地导出"
    width="506px"
    centered
    :ok-button-props="{
      loading: loading
    }"
    @cancel="close"
    @ok="ok"
  >
    <a-form ref="formRef" :model="formState">
      <a-form-item name="exportFile" label="数据导出范围">
        <a-radio-group v-model:value="formState.exportFile" class="ml-24">
          <div class="h-36 flc">
            <a-radio :value="false">仅导出标注文件</a-radio>
          </div>
          <div class="h-36 flc">
            <a-radio :value="true">导出全部数据，包含源文件及已有的标注文件</a-radio>
          </div>
        </a-radio-group>
      </a-form-item>
      <a-form-item name="exportFormat" label="数据导出格式">
        <a-radio-group v-model:value="formState.exportFormat" disabled class="ml-24">
          <div class="h-36 flc">
            <a-radio :value="true">平台默认格式</a-radio>
          </div>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'

  import { dmpTaskApi } from '@/services/api'
  import { waitLoading } from '@/utils'
  interface FormState {
    markId: string
    exportFile: boolean
    exportFormat: boolean
  }

  const visible = ref(false)
  const formState = ref<FormState>({
    markId: '',
    exportFile: false,
    exportFormat: true
  })
  const formRef = ref()

  const { loading, runAsync: runExport } = useRequest<ResponseData<string>>(dmpTaskApi.localExport)

  const open = (record: any) => {
    visible.value = true
    formState.value.markId = record.id
  }
  const close = () => {
    visible.value = false
    formRef.value.resetFields()
  }

  const ok = async () => {
    const res = await waitLoading(runExport(formState.value, { timeout: 300000 }), {
      loadingText: '数据准备中,请耐心等待...',
      successText: '开始下载',
      errorText: '文件导出失败'
    })

    console.log(res)

    if (res) {
      window.open(res?.data)
    }

    close()
  }

  defineExpose({
    open,
    close
  })
</script>
